package com.kaiwu.tc.factory;

import com.kaiwu.tc.annotations.Autowired;
import com.kaiwu.tc.annotations.Service;

import java.io.File;
import java.lang.reflect.Field;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    private static Map<String,Object> map = new HashMap<>();
    private static List<String> list = new ArrayList<String>();

    private static String scanPackage = "com.kaiwu.tc".replace('.', '/');

    static {
        try {
            Enumeration<URL> dirs=Thread.currentThread().getContextClassLoader().getResources(scanPackage);
            while(dirs.hasMoreElements()){
                URL url = dirs.nextElement();

                String protocol = url.getProtocol();
                if ("file".equals(protocol)){
                    //文件扫描
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    File file = new File(filePath);
                    getClassName(file);
                }

                if ("jar".equals(protocol)) {
                    JarFile jar= ((JarURLConnection) url.openConnection()).getJarFile();
                    //获取文件，需要递归处理文件夹
                    Enumeration<JarEntry> entries = jar.entries();
                    //TODO
                }
            }

            for(String str:list){
                System.out.println(str);
                Class<?> c = Class.forName(str);
                boolean isAnno = c.isAnnotationPresent(Service.class);
                if(isAnno){
                    Service d = c.getAnnotation(Service.class);
                    Object obj = c.newInstance();
                    System.out.println(d.value());
                    if ("".equalsIgnoreCase(d.value())){
                        map.put(c.getName(), obj);
                        if (c.getInterfaces() != null && c.getInterfaces().length > 0){
                            map.put(c.getInterfaces()[0].getName(), obj);
                        }
                    }else {
                        map.put(d.value(), obj);
                    }
                }
            }

            for (Map.Entry<String, Object> entry: map.entrySet()){
                Object parentObject = entry.getValue();
                Field[] fields = parentObject.getClass().getDeclaredFields();
                for (Field field: fields){
                    boolean isAnno = field.isAnnotationPresent(Autowired.class);
                    if (isAnno){
                        Autowired d = field.getAnnotation(Autowired.class);
                        Object value = null;
                        if ("".equalsIgnoreCase(d.value())){
                            value = map.get(field.getType().getName());
                        }else {
                            value = map.get(d.value());
                        }
                        field.setAccessible(true);
                        try {
                            field.set(parentObject, value);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static  Object getBean(String id) {
        return map.get(id);
    }


    private static void getClassName(File file) {
        if(file.isDirectory()){
            File[] files =file.listFiles(pathname -> pathname.getName().endsWith(".class")||pathname.isDirectory());
            for(File f:files){
                getClassName(f);
            }

        }else{
            String name =file.getAbsolutePath();
            name = name.substring(name.lastIndexOf("com/kaiwu/tc")).replaceAll("/", ".");
            name = name.substring(0, name.lastIndexOf("."));
            list.add(name);
        }
    }

}
